//
//  WYWRemoteAudioFile.m
//  WYWPlayer
//
//  Created by Mr.Run on 2017/11/9.
//  Copyright © 2017年 Mr.Run. All rights reserved.
//

#import "WYWRemoteAudioFile.h"
#import <MobileCoreServices/MobileCoreServices.h>

#define kCachePath NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject
#define kTempPath NSTemporaryDirectory()

@implementation WYWRemoteAudioFile

+(NSString *)cacheFilePath:(NSURL *)url{
    return [kCachePath stringByAppendingPathComponent:url.lastPathComponent];
}

+(long long)cacheFileSize:(NSURL *)url{
    
    if (![self cacheFileExists:url]) {
        return 0;
    }
    
    NSString *filePath = [self cacheFilePath:url];
    NSDictionary *fileInfoDic = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
    return [fileInfoDic[NSFileSize] longLongValue];
}

+(BOOL)cacheFileExists:(NSURL *)url{
    NSString *filePath = [self cacheFilePath:url];
    return [[NSFileManager defaultManager] fileExistsAtPath:filePath];
}

+(NSString *)tmpFilePath:(NSURL *)url{
    
    return [kTempPath stringByAppendingPathComponent:url.lastPathComponent];
}

+(long long)tmpFileSize:(NSURL *)url{
    if (![self tmpFileExists:url]) {
        return 0;
    }
    
    NSString *filePath = [self tmpFilePath:url];
    NSDictionary *fileInfoDic = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
    return [fileInfoDic[NSFileSize] longLongValue];
}


+(BOOL)tmpFileExists:(NSURL *)url{
    NSString *filePath = [self tmpFilePath:url];
    return [[NSFileManager defaultManager] fileExistsAtPath:filePath];
}

+(void)clearTmpFile:(NSURL *)url{
    NSString *tmpPath = [self tmpFilePath:url];
    
    BOOL isDirectory = YES;
    BOOL isEx = [[NSFileManager defaultManager] fileExistsAtPath:tmpPath isDirectory:&isDirectory];
    if (isEx && !isDirectory) {
        [[NSFileManager defaultManager] removeItemAtPath:tmpPath error:nil];
    }
}

+(NSString *)contentType:(NSURL *)url{
    NSString *path = [self cacheFilePath:url];
    NSString *fileExtension = path.pathExtension;
    
    CFStringRef contentTypeRef = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef _Nonnull)(fileExtension), NULL);
    NSString *contentType = CFBridgingRelease(contentTypeRef);
    return contentType;
}

+(void)moveTmpPathToCachePath:(NSURL *)url{
    
    NSString *tmpPath = [self tmpFilePath:url];
    NSString *cachePath = [self cacheFilePath:url];
    [[NSFileManager defaultManager] moveItemAtPath:tmpPath toPath:cachePath error:nil];
    
}

@end
